package com.ww.exercise.coroutine.easy.q7

import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicInteger

fun main() = runBlocking {
    // 1.创建Java自定义线程池（固定5个线程）
    val threadCounter = AtomicInteger(0)
    val customThreadPool = Executors.newFixedThreadPool(5) { runnable ->
        // 为线程设置自定义名称，方便识别
        Thread(runnable, "CustomPool-Thread-${threadCounter.incrementAndGet()}")
    }

    // 2.将线程池转换为协程调度器
    val customDispatcher = customThreadPool.asCoroutineDispatcher()

    try {
        println("主线程：${Thread.currentThread().name}")

        // 3.在自定义调度器上启动多个协程
        repeat(10) { index ->
            launch(customDispatcher) {
                println("任务$index 运行在：${Thread.currentThread().name}")
                Thread.sleep(100)
            }
        }

        // 4.使用withContext在自定义调度器上执行代码块
        val result = withContext(customDispatcher) {
            println("withContext运行在：${Thread.currentThread().name}")
            "处理完成"
        }
        println("结果：$result")
    } finally {
        // 5.关闭线程池（避免资源泄漏）
        customThreadPool.shutdown()
    }
}